import Vue from 'vue'
import Vuex from 'vuex'
// 导入日志插件
import createLogger from 'vuex/dist/logger'
//导入持久化插件
import createPersistedState from "vuex-persistedstate";

// 导入Toast组件，轻提示
import { Toast, Dialog } from 'vant'
import { fav, favlist, unfav, shopcar_list, shopcar_clear, shopcar_add, shopcar_sub, address_list, address_add, address_del, address_edit } from '@/utils/api'

Vue.use(Vuex)

export default new Vuex.Store({
  // namespaced: true,
  state: {//负责存储数据( 存储在这里的数据是响应式数据, 当这里的数据发生改变时, 任何使用到该数据的组件都会自动更新 )
    collectlist: [],//收藏列表
    // 每次刷新就从本地存储中去取本地存储中存的值，如果没有就返回一个空数组
    // collectlist: localStorage.getItem('vuex') ? JSON.parse(localStorage.getItem('vuex')).collectlist : []
    // 获取本地存储中的用户id
    userid: '',
    shopcarlist: [],
    addresslist: [],
  },
  getters: {

  },
  mutations: {//定义同步方法( 特点: 同步方法可以直接修改state中的数据 )
    //同步方法 参数一: 保存数据的state对象
    //同步方法 参数二: 调用同步方法时 传入的参数
    // 在登录成功之后调用该同步方法将用户的userid保存在vuex中
    add_userid(state) {
      // 获取用户的userid
      state.userid = JSON.parse(localStorage.getItem('userinfo')).id;
      console.log(state.userid);
    },
    collect(state, payload) {//收藏一个店铺
      state.collectlist.push(payload);
      // 每次刷新都会导致数据丢失，所以把每次的数据要存进本地存储中
      // localStorage.setItem('vuex', JSON.stringify(state));
      Toast({
        message: '已收藏!',
        icon: 'passed',
      });
    },
    cancel_collect(state, payload) {//取消收藏一个店铺
      var index = state.collectlist.findIndex((item) => {
        // console.log(payload.mtWmpoiId);
        return item.mtWmPoiId == payload.mtWmPoiId;
      })
      if (index != -1) {
        state.collectlist.splice(index, 1);
      }
      localStorage.setItem('vuex', JSON.stringify(state));
      Toast({
        message: '已取消收藏!',
        icon: 'passed',
      });
    },
    // 保存收藏列表
    save_favlist(state, payload) {
      state.collectlist = payload;
    },

    // 保存购物车列表
    save_shopcarlist(state, payload) {
      state.shopcarlist = payload;
    },

    // 清除购物车
    clear(state) {
      state.shopcarlist = [];
    },

    // 购物车数量加1
    shopcar_add(state, payload) {
      var index = state.shopcarlist.findIndex((item) => {
        return item.id == payload.id;
      })
      if (index != -1) {//f该商品已经在购物车中
        state.shopcarlist[index].count++;
      } else {//该商品是第一次加入购物车中
        // 深拷贝商品对象，对深拷贝的对象添加count属性，值为1
        var good = JSON.parse(JSON.stringify(payload))
        good.count = 1
        state.shopcarlist.push(good);
      }
    },
    // 购物车数量减1
    shopcar_sub(state, payload) {
      var good = state.shopcarlist.find((item) => {
        return item.id == payload.id;
      })

      var index = state.shopcarlist.findIndex((item) => {
        return item.id == payload.id;
      })
      if (good) {//该商品不在购物车中
        console.log(good.count);
        if (good.count > 1) {
          good.count--;
        } else if (good.count == 1) {
          state.shopcarlist.splice(index, 1)
        }
      }
    },

    // 保存地址列表
    address_list(state, payload) {
      state.addresslist = payload;
    },

    // 添加地址
    address_add(state, payload) {
      state.addresslist.unshift(payload);
    },

    // 删除地址
    address_del(state, payload) {
      var index = state.addresslist.findIndex((item) => {
        return item.id = payload.addressid
      })
      if (index != -1) {
        state.addresslist.splice(index, 1);
      }

    },
    // 修改地址
    address_edit(state, payload) {
      console.log(payload);
      var index = state.addresslist.findIndex((item) => {
        console.log(item.id);
        console.log(payload.id);
        return item.id == payload.id;
      })
      console.log(index);
      if (index != -1) {
        state.addresslist.splice(index, 1, { userid: state.userid, id: payload.id, address: payload.address, phone: payload.phone, name: payload.name });
      }
    }
  },
  actions: {//定义异步方法( 特点: 异步方法内部可以书写异步代码[ajax,定时器,事件监听] , 但是如果想要修改state中的数据必须间接调用同步方法执行修改 )
    //异步方法 参数一: 当前仓库的实例对象
    //异步方法 参数二: 调用异步方法时 传入的参数

    // 获取收藏列表
    request_favlist(store) {
      // 发请求 获取当前用户的收藏列表
      // console.log(store.state.userid);
      favlist({ userid: store.state.userid }).then((res) => {
        console.log(res.data);
        store.commit('save_favlist', res.data.list);
      })
    },
    // 收藏店铺，调用该异步方法时传入店铺
    request_fav(store, payload) {
      // console.log(store.state.userid);
      fav({ userid: store.state.userid, shopid: payload.mtWmPoiId }).then((res) => {
        console.log(res.data);
        if (res.data.code == 200) {
          store.commit('collect', payload);
        }
      })
    },
    // 取消收藏店铺
    request_unfav(store, payload) {
      unfav({ userid: store.state.userid, shopid: payload.mtWmPoiId }).then((res) => {
        // console.log(res.data);
        if (res.data.code == 200) {
          store.commit('cancel_collect', payload);
        }
      })
    },
    // 购物车列表
    request_shopcarlist(store) {
      shopcar_list({ userid: store.state.userid }).then((res) => {
        // console.log(res.data);
        if (res.data.code == 200) {
          store.commit('save_shopcarlist', res.data.list);
        }
      })
    },
    // 发请求，清空购物车列表
    request_clear(store) {
      shopcar_clear({ userid: store.state.userid }).then((res) => {
        if (res.data.code == 200) {
          store.commit('clear');
        }
      })
    },
    // 发请求，数量加1
    request_shopcar_add(store, payload) {
      shopcar_add({ userid: store.state.userid, goodid: payload.id }).then((res) => {
        if (res.data.code == 200) {
          store.commit('shopcar_add', payload);
        }
      })
    },
    // 发请求，数量减1
    request_shopcar_sub(store, payload) {
      shopcar_sub({ userid: store.state.userid, goodid: payload.id }).then((res) => {
        if (res.data.code == 200) {
          store.commit('shopcar_sub', payload);
        }
      })
    },
    // 地址列表
    request_address_list(store) {
      address_list({ userid: store.state.userid }).then((res) => {
        if (res.data.code == 200) {
          store.commit('address_list', res.data.list);
        }
      })
    },
    // 地址列表
    request_address_list(store) {
      address_list({ userid: store.state.userid }).then((res) => {
        if (res.data.code == 200) {
          store.commit('address_list', res.data.list);
        }
      })
    },

    // 添加地址
    // userid 用户id 必须传; address 联系地址 必须传; phone 联系方式 必须传; name 联系人 必须传
    requset_address_add(store, payload) {
      address_add(payload).then((res) => {
        if (res.data.code == 200) {
          // store.commit('address_add',{ userid: store.state.userid, address: payload.address, phone: payload.phone, name: payload.name });
          address_list({ userid: store.state.userid }).then((res) => {
            Toast({
              message: '地址添加成功!',
              icon: 'success',
            });
            if (res.data.code == 200) {
              store.commit('address_list', res.data.list);
            }
          })
        }
      })
    },

    // 删除地址
    request_address_del(store, payload) {
      console.log(payload);
      address_del(payload).then((res) => {
        if (res.data.code == 200) {
          store.commit('address_del', payload);
          Dialog.confirm({
            title: '删除地址',
            message: '确认删除该收货地址吗？',
            beforeClose(action, done) {
              if (action === 'confirm') {
                address_list({ userid: store.state.userid }).then((res) => {
                  if (res.data.code == 200) {
                    store.commit('address_list', res.data.list);
                  }
                  Toast({
                    message: '地址删除成功!',
                    icon: 'success',
                  });
                  done()
                })
              } else {
                done();
              }
            }
          });

        }
      })
    },

    // 修改地址
    request_address_edit(store, payload) {
      console.log(payload);
      console.log(payload.id);
      console.log(store.state.userid);
      address_edit({ userid: store.state.userid, addressid: payload.id, address: payload.address, phone: payload.phone, name: payload.name }).then((res) => {
        Toast({
          message: '地址修改成功!',
          icon: 'success',
        });
        if (res.data.code == 200) {
          store.commit('address_edit', payload);
        }
      })
    }
  },
  modules: {
  },
  //配合其他插件 管理vuex中state内部的数据
  plugins: [createLogger(), createPersistedState()]
})
